from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import F
from .models import Node, Connection
import json
import logging

logger = logging.getLogger(__name__)

@csrf_exempt
def network(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            action = data.get('action')
            
            if action == 'add_node':
                node = Node.objects.create(
                    label=data.get('label', ''),
                    description=data.get('description', ''),
                    x_position=data['x_position'],
                    y_position=data['y_position'],
                    size=data.get('size', 10),
                    color=data.get('color', '#1f77b4')
                )
                return JsonResponse({'status': 'success', 'id': node.id})
                
            elif action == 'add_connection':
                logger.info(f"Received connection data: {data}")
                try:
                    source = Node.objects.get(id=data['source_id'])
                    target = Node.objects.get(id=data['target_id'])
                    connection = Connection.objects.create(
                    source_id=source.id,
                    target_id=target.id,
                        weight=data.get('weight', 1)
                    )
                    logger.info(f"Created connection from {source.id} to {target.id}")
                    return JsonResponse({
                        'status': 'success',
                        'logs': [
                            f"Received connection request: {data['source_id']} -> {data['target_id']}",
                            f"Found source node: {source.id}",
                            f"Found target node: {target.id}",
                            f"Created connection with ID: {connection.id}"
                        ]
                    })
                except Exception as e:
                    logger.error(f"Failed to create connection: {str(e)}")
                    return JsonResponse({
                        'status': 'error', 
                        'message': str(e),
                        'logs': [f"Error creating connection: {str(e)}"]
                    }, status=400)
                
            elif action == 'remove_node':
                node = Node.objects.filter(id=data['id'])
                if not node.exists():
                    return JsonResponse({'status': 'error', 'message': '节点不存在'}, status=404)
                node.delete()
                return JsonResponse({'status': 'success'})
                
            elif action == 'remove_connection':
                conn = Connection.objects.filter(
                    source_id=data['source_id'],
                    target_id=data['target_id']
                )
                if not conn.exists():
                    return JsonResponse({'status': 'error', 'message': '连接不存在'}, status=404)
                conn.delete()
                return JsonResponse({'status': 'success'})
                
            elif action == 'update_node_description':
                try:
                    node = Node.objects.get(id=data['id'])
                    node.description = data['description']
                    node.desc_type = data['desc_type']
                    node.save()
                    return JsonResponse({'status': 'success'})
                except Node.DoesNotExist:
                    return JsonResponse({'status': 'error', 'message': '节点不存在'}, status=404)
                except Exception as e:
                    return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
                
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
    
    # GET请求返回初始数据
    try:
        nodes = list(Node.objects.values('id', 'label', 'description', 'desc_type', 'x_position', 'y_position', 'size', 'color'))
        connections = list(Connection.objects.values(
            'source_id', 
            'target_id', 
            'weight', 
            is_directed=F('directed')  # 使用不同别名避免冲突
        ))
        
        # 转换布尔值为小写字符串
        for conn in connections:
            if 'is_directed' in conn:
                conn['directed'] = 'true' if conn['is_directed'] else 'false'
                del conn['is_directed']  # 删除临时字段
        
        # 确保每个节点都包含desc_type字段
        for node in nodes:
            if 'desc_type' not in node:
                node['desc_type'] = 'plain'
        
        return render(request, 'network.html', {
            'initial_data': {
                'nodes': nodes,
                'connections': connections
            }
        })
    except Exception as e:
        logger.error(f"Failed to prepare initial data: {str(e)}", exc_info=True)
        return JsonResponse({
            'status': 'error',
            'message': str(e),  # 返回具体错误信息
            'detail': 'Failed to load initial data. Check server logs for details.'
        }, status=500)